﻿using System.Collections.Generic;
using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class CodeBlockParser
        : ExpressionParser
    {

        public CodeBlockParser()
        {
            BodyParsers = new List<ExpressionParser>();
        }

        public override Expression Parse(Token[] tokens, int index)
        {
            if (tokens[index].Type == TokenType.CurlyOpen)
            {
                var codeBlock = new CodeBlock {OpenBracket = tokens[index]};
                codeBlock.StringIndex = codeBlock.OpenBracket.Index;
                codeBlock.Add(new SingleToken() { Token = codeBlock.OpenBracket});
                var closeIndex = ParseUtils.FindClosingBracket(tokens, index, TokenType.CurlyOpen, TokenType.CurlyClose);
                if (closeIndex.HasValue)
                {
                    codeBlock.CloseBracket = tokens[closeIndex.Value];
                    codeBlock.TokenLength = closeIndex.Value - index + 1;
                }
                else
                {
                    codeBlock.TokenLength = tokens.Length - index;
                }
                codeBlock.Body = ParseSubExpression(tokens, index + 1, codeBlock.TokenLength - (closeIndex.HasValue? 2 : 1), BodyParsers);
                if (codeBlock.Body != null) codeBlock.Add(codeBlock.Body);
                if (codeBlock.CloseBracket != null) codeBlock.Add(new SingleToken() { Token = codeBlock.CloseBracket});

                var lastToken = tokens[index + codeBlock.TokenLength - 1];
                codeBlock.StringLength = lastToken.Index + lastToken.Value.Length - codeBlock.StringIndex;

                return codeBlock;
            }
            return null;
        }

        public List<ExpressionParser> BodyParsers { get; set; }

    }
}
